import React, {useEffect, useState} from 'react';
import {
    TimePicker, Breadcrumb, Card, Form,
    Radio, Select, Button, DatePicker, Table, Tag, Space, Image, Popconfirm
} from "antd";
import 'moment/locale/zh-cn'
import locale from 'antd/es/date-picker/locale/zh_CN'
import './index.scss'
import {EditOutlined, DeleteOutlined} from "@ant-design/icons";
import img404 from '@/assets/error.png'
import {http, mockRequest} from "@/utils";
import {Link, useNavigate} from "react-router-dom";
import {useStore} from "@/store";
import {observer} from "mobx-react-lite";

const Article = () => {

    //面包屑
    const items = [
        {label: <Link to="/"> 首页</Link>, key: '/'}, // 菜单项务必填写 key
        {label: <Link to="/article"> 内容管理</Link>, key: '/article'},
    ];

    //时间选择
    const {RangePicker} = DatePicker;

    //编辑按钮的跳转
    const navigate = useNavigate()
    const goPublish = (data) => {
        navigate(`/publish?id=${data.id}`)
    }

    //表格每个列的标题
    const columns = [
        {
            title: '封面',
            dataIndex: 'cover',
            width: 120,
            render: cover => {
                return <Image src={cover.images || img404} width={180} height={160} alt=""/>
            }
        },
        {
            title: '标题',
            dataIndex: 'title',
            width: 220
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: data => <Tag color="green">审核通过</Tag>
        },
        {
            title: '发布时间',
            dataIndex: 'pubdate'
        },
        {
            title: '阅读数',
            dataIndex: 'read_count'
        },
        {
            title: '评论数',
            dataIndex: 'comment_count'
        },
        {
            title: '点赞数',
            dataIndex: 'like_count'
        },
        {
            title: '操作',
            render: data => {
                return (
                    <Space size="middle">
                        {/*编辑操作*/}
                        <Button
                            onClick={() => goPublish(data)}
                            type="primary"
                            shape="circle"
                            icon={<EditOutlined/>}/>
                        {/*删除操作*/}
                        <Popconfirm
                            title="确认删除该条文章吗?"
                            onConfirm={() => delArticle(data)}
                            okText="确认"
                            cancelText="取消">
                            <Button
                                type="primary"
                                danger
                                shape="circle"
                                icon={<DeleteOutlined/>}/>
                        </Popconfirm>
                    </Space>
                )
            }
        }
    ]

    const {channelStore} = useStore()


    //文章列表管理,统一管理数据
    const [articleList, setArticleList] = useState({
        list: [],
        count: 0
    })

    //文章参数管理
    const [params, setParams] = useState({
        page: 1,
        per_page: 3,
    })

    //如果异步精求函数需要依赖一些数据的变化而重新执行
    //推荐把它写到内部
    //统一不抽离函数到外面只要涉及到异步请求的函数都放到useEffect内部
    //本质区别:写到外面每次组件更新都会重新进行函数初始化这本身就是一次性能消耗
    //而写到useEffect中只会在依赖项发生变化的时候函数才会进行重新初始化
    //避免性能损失
    useEffect(() => {
        const getArticleList = async () => {
            const res = await http.get('/mp/articles', {params})
            const {results, total_count} = res.data
            setArticleList({
                list: results,
                count: total_count
            })
        }
        getArticleList()
    }, [params])

    //表单的按钮
    const onFinish = (values) => {
        const {channel_id, date, status} = values
        const _params = {}
        if (status !== -1) {
            _params.status = status
        }
        if (channel_id) {
            _params.channel_id = channel_id
        }
        if (date) {
            _params.begin_pubdate = date[0].format('YYYY-MM-DD')
            _params.end_pubdate = date[1].format('YYYY-MM-DD')
        }
        //修改params数据 引起接口的重新发送 对象的合并是一个整体覆盖
        setParams({
            ...params,
            ..._params
        })
    }

    //分页器的点击事件
    const pageChange = (page) => {
        // 拿到当前页参数 修改params 引起接口更新
        setParams({
            ...params,
            page
        })
    }

    //删除功能
    const delArticle = async (data) => {
        // const res=await mockRequest.delete(`/mp/article/${data.id}`)
        // console.log(res)
        // let aList = articleList.list.filter(item => item.id !== data.id)
        // setArticleList({
        //     list: aList,
        //     count: aList.length
        // })
        await http.delete(`/mp/articles/${data.id}`)
        // 更新列表
        setParams({
            page: 1,
            per_page: 10
        })
    }


    return (
        <div>
            <Card style={{marginBottom: 20}}
                  title={
                      <Breadcrumb separator='>'>
                          {items.map(item =>
                              <Breadcrumb.Item key={item.key}>
                                  {item.label}
                              </Breadcrumb.Item>)}
                      </Breadcrumb>}>

                <Form onFinish={onFinish} initialValues={{status: null}}>
                    <Form.Item label="状态" name="status">
                        <Radio.Group>
                            <Radio value={-1}>全部</Radio>
                            <Radio value={0}>草稿</Radio>
                            <Radio value={1}>待审核</Radio>
                            <Radio value={2}>审核通过</Radio>
                            <Radio value={3}>审核失败</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item label="频道" name={"channel_id"}>
                        <Select
                            placeholder='请选择文章频道'
                            style={{width: 150,}}
                            options={
                                channelStore.channelList.map(item => ({value: item.id, label: item.name}))
                            }
                        />
                    </Form.Item>
                    <Form.Item label="日期" name="date">
                        <RangePicker
                            locale={locale}
                            showTime={{format: 'HH:mm'}}
                            format="YYYY-MM-DD HH:mm">
                        </RangePicker>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" style={{marginLeft: 50}}>
                            筛选
                        </Button>
                    </Form.Item>
                </Form>
            </Card>

            <Card title={`根据筛选条件共查询到 ${articleList.count} 条结果：`}>
                <Table
                    rowKey="id"
                    columns={columns}
                    dataSource={articleList.list}
                    pagination={
                        {
                            position: ['bottomCenter'],
                            pageSize: params.per_page,
                            total: articleList.count,
                            onChange: pageChange
                        }
                    }
                />
            </Card>
        </div>
    )
};

export default observer(Article);